#!/bin/bash
# 系统配置备份脚本（需要管理员权限）
# 使用方法: sudo ./system_config_backup.sh

if [ "$EUID" -ne 0 ]; then
    echo "此脚本需要管理员权限，请使用: sudo ./system_config_backup.sh"
    exit 1
fi

BASE_BACKUP_DIR="/Users/m/Downloads/netWorkBackUp"
BACKUP_DIR="$BASE_BACKUP_DIR/netWork-backup-$(date +%y%m%d_%H%M%S)"
mkdir -p "$BACKUP_DIR"

echo "开始备份系统网络配置文件..."
echo "备份目录: $BACKUP_DIR"

# 备份SystemConfiguration目录
if [ -d "/Library/Preferences/SystemConfiguration" ]; then
    echo "备份SystemConfiguration目录..."
    cp -r /Library/Preferences/SystemConfiguration "$BACKUP_DIR/"
    chown -R $(logname) "$BACKUP_DIR/SystemConfiguration"
    echo "✅ SystemConfiguration目录已备份"
else
    echo "❌ SystemConfiguration目录不存在"
fi

# 备份其他重要的系统网络配置
echo "备份其他系统网络配置..."

# 网络配置文件
if [ -f "/etc/ppp/options" ]; then
    cp /etc/ppp/options "$BACKUP_DIR/ppp_options.txt" 2>/dev/null
fi

# Kerberos配置
if [ -f "/etc/krb5.conf" ]; then
    cp /etc/krb5.conf "$BACKUP_DIR/krb5_conf.txt" 2>/dev/null
fi

# SSH配置
if [ -f "/etc/ssh/ssh_config" ]; then
    cp /etc/ssh/ssh_config "$BACKUP_DIR/ssh_config.txt" 2>/dev/null
fi

# 创建恢复脚本
cat > "$BACKUP_DIR/restore_system_config.sh" << 'EOF'
#!/bin/bash
# 系统配置恢复脚本

if [ "$EUID" -ne 0 ]; then
    echo "此脚本需要管理员权限，请使用: sudo ./restore_system_config.sh"
    exit 1
fi

echo "开始恢复系统网络配置..."

# 备份当前配置
if [ -d "/Library/Preferences/SystemConfiguration" ]; then
    cp -r /Library/Preferences/SystemConfiguration "/Library/Preferences/SystemConfiguration.backup.$(date +%Y%m%d_%H%M%S)"
    echo "✅ 当前配置已备份"
fi

# 恢复SystemConfiguration
if [ -d "SystemConfiguration" ]; then
    echo "恢复SystemConfiguration目录..."
    cp -r SystemConfiguration/* /Library/Preferences/SystemConfiguration/
    echo "✅ SystemConfiguration已恢复"
else
    echo "❌ 找不到SystemConfiguration目录"
fi

# 恢复其他配置文件
if [ -f "ppp_options.txt" ]; then
    cp ppp_options.txt /etc/ppp/options 2>/dev/null
    echo "✅ PPP配置已恢复"
fi

if [ -f "krb5_conf.txt" ]; then
    cp krb5_conf.txt /etc/krb5.conf 2>/dev/null
    echo "✅ Kerberos配置已恢复"
fi

if [ -f "ssh_config.txt" ]; then
    cp ssh_config.txt /etc/ssh/ssh_config 2>/dev/null
    echo "✅ SSH配置已恢复"
fi

echo "系统配置恢复完成！请重启系统。"
EOF

chmod +x "$BACKUP_DIR/restore_system_config.sh"

# 创建信息文件
cat > "$BACKUP_DIR/system_config_info.txt" << EOF
系统网络配置备份信息
===================
备份时间: $(date)
备份目录: $BACKUP_DIR

备份内容:
- SystemConfiguration/ - 系统网络配置目录
- ppp_options.txt - PPP配置（如果存在）
- krb5_conf.txt - Kerberos配置（如果存在）
- ssh_config.txt - SSH配置（如果存在）

恢复方法:
sudo ./$BACKUP_DIR/restore_system_config.sh

注意事项:
- 需要管理员权限
- 恢复前会自动备份当前配置
- 恢复后需要重启系统
EOF

echo "✅ 系统配置备份完成！"
echo "备份位置: $BACKUP_DIR"
echo "恢复方法: sudo $BACKUP_DIR/restore_system_config.sh"
